<template>
  <div class="page-container">
    <h2 class="page-title">通知与提醒</h2>
    <el-space class="button-group">
      <el-button type="primary" @click="showSendDialog = true">发送通知</el-button>
    </el-space>

    <el-card class="notification-card">
      <el-timeline>
        <el-timeline-item v-for="notice in notifications" :key="notice.id" :timestamp="formatTime(notice.createdAt)"
          placement="top">
          <el-card :class="{ 'unread-notice': !notice.isRead }">
            <div class="notice-header">
              <h4>{{ formatType(notice.type) }}</h4>
              <el-button type="danger" size="small" @click="removeNotification(notice.id)">
                删除
              </el-button>
            </div>
            <p>{{ notice.content }}</p>
          </el-card>
        </el-timeline-item>
      </el-timeline>
    </el-card>

    <!-- 发送通知对话框保持不变 -->
    <el-dialog v-model="showSendDialog" title="发送通知" width="50%">
      <el-form :model="newNotification" label-width="100px">
        <el-form-item label="通知内容" prop="content" required>
          <el-input v-model="newNotification.content" type="textarea" :rows="4" placeholder="请输入通知内容" clearable />
        </el-form-item>

        <el-form-item label="通知类型" prop="type" required>
          <el-select v-model="newNotification.type" placeholder="请选择通知类型" style="width: 100%" clearable>
            <el-option label="审批通知" :value="1" />
            <el-option label="提醒通知" :value="2" />
            <el-option label="系统通知" :value="3" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showSendDialog = false">取消</el-button>
        <el-button type="primary" @click="sendNewNotification" :loading="sending">
          发送
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import dayjs from 'dayjs'
import { getSentNotifications, sendNotification, deleteNotification } from '@/api/notification' // 确保导入发送通知的API
import { ElMessage,ElMessageBox } from 'element-plus'

// 通知列表数据
const notifications = ref([])
const showSendDialog = ref(false)
const userMap = ref({}) // 存储用户信息缓存

// 初始化新的通知对象
const newNotification = ref({
  content: '',
  type: '' // 确保这里有一个默认值，或者可以在模板中使用v-model时处理
})

// 格式化时间
const formatTime = (timeStr) => {
  return dayjs(timeStr).format('YYYY-MM-DD HH:mm:ss')
}

// 格式化通知类型
const typeMap = {
  approval: '审批通知',
  reminder: '提醒通知',
  system: '系统通知'
}
const formatType = (type) => {
  return typeMap[type] || type
}

// 获取发送者名称
const getSenderName = (authorId) => {
  return userMap.value[authorId]?.username || `用户ID: ${authorId}`
}

// 获取通知列表
const fetchNotifications = async () => {
  try {
    const response = await getSentNotifications()
    if (response?.data?.code === 200) {
      // 使用 Map 来去重，key 为 content 和 type 的组合
      const uniqueNotifications = new Map()

      response.data.data.forEach(notification => {
        // 使用内容和类型的组合作为唯一标识
        const key = `${notification.content}_${notification.type}`
        if (!uniqueNotifications.has(key)) {
          uniqueNotifications.set(key, notification)
        } else {
          // 如果有重复，保留时间最新的那条通知
          const existing = uniqueNotifications.get(key)
          if (new Date(notification.createdAt) > new Date(existing.createdAt)) {
            uniqueNotifications.set(key, notification)
          }
        }
      })

      // 将 Map 转换为数组并按时间降序排序
      notifications.value = Array.from(uniqueNotifications.values())
        .sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
    }
  } catch (error) {
    console.error('获取通知列表失败:', error)
    ElMessage.error('获取通知列表失败')
  }
}

// 发送新通知
const sendNewNotification = async () => {
  if (!newNotification.value.content || !newNotification.value.type) {
    ElMessage.warning('请填写所有必填字段!')
    return
  }

  try {
    const response = await sendNotification(1, newNotification.value)
    if (response.data.code === 200) {
      ElMessage.success('通知发送成功')
      showSendDialog.value = false
      fetchNotifications() // 重新加载通知列表
    } else {
      ElMessage.error('通知发送失败')
    }
  } catch (error) {
    console.error('发送通知失败:', error)
    ElMessage.error('发送通知失败')
  }
}

// 删除所有相同内容和类型的通知
const removeNotification = async (id) => {
  try {
    // 首先获取完整的通知列表（不经过前端去重）
    const fullResponse = await getSentNotifications();
    if (fullResponse?.data?.code !== 200) {
      ElMessage.error('获取通知列表失败');
      return;
    }

    // 找到要删除的目标通知
    const targetNotice = fullResponse.data.data.find(n => n.id === id);
    if (!targetNotice) {
      ElMessage.warning('未找到要删除的通知');
      return;
    }

    // 确认对话框
    await ElMessageBox.confirm(
      `确定删除"${targetNotice.content}"(${formatType(targetNotice.type)})通知吗?`,
      '删除确认',
      { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
    );

    // 找出所有相同内容和类型的通知ID
    const noticesToDelete = fullResponse.data.data.filter(n => 
      n.content === targetNotice.content && 
      n.type === targetNotice.type
    );

    // 批量删除
    const deleteResults = await Promise.all(
      noticesToDelete.map(notice => deleteNotification(notice.id))
    );

    // 检查删除结果
    if (deleteResults.every(res => res.data.code === 200)) {
      ElMessage.success(`成功删除${noticesToDelete.length}条通知`);
      // 重新获取并更新通知列表
      await fetchNotifications();
    } else {
      ElMessage.error('部分通知删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除通知失败:', error);
      ElMessage.error('删除通知失败');
    }
  }
}

// 初始化加载
onMounted(() => {
  fetchNotifications()
})
</script>

<style scoped>
.notification-card {
  max-width: 100%;
  margin-top: 20px;
}

.el-timeline {
  padding-left: 20px;
}

.notice-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.notice-footer {
  margin-top: 10px;
  font-size: 12px;
  color: #888;
}

.unread-notice {
  border-left: 3px solid #f56c6c;
  background-color: #fef0f0;
}
</style>